/* global window */
import modelExtend from 'dva-model-extend'
import { message } from 'antd'
import { querylist, remove, report, reported } from 'services/transactionReceipt/transactionReceipt.js'
import { pageModel } from './common'

export default modelExtend(pageModel, {
  namespace: 'transactionReport',
  state: {
    currentItem: {},
    modalVisible: false,
    editType: 'create',
    selectedRowKeys: [],
  },
  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/transactionreport/') {
          const payload = location.query || { page: 1 }
          dispatch({
            type: 'query',
            payload,
          })
        }
      })
    },
  },
  effects: {
    * query ({ payload = {} }, { call, put }) {
      let sendData = { status: '4' }
      Object.assign(sendData, payload)
      sendData.currentPage = payload.page
      const data = yield call(querylist, sendData)
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.data.total,
            },
          },
        })
      }
    },
    * delete ({ payload }, { call, put, select }) {
      const data = yield call(remove, { id: payload })
      const { selectedRowKeys } = yield select(_ => _.transactionReport)
      if (data.success) {
        message.success('delete success')
        yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } })
        yield put({ type: 'query' })
      } else {
        message.error('delete failed')
        throw data
      }
    },
    * multiDelete ({ payload }, { call, put }) {
      const data = yield call(remove, payload)
      if (data.success) {
        message.success('delete success')
        yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
        yield put({ type: 'query' })
      } else {
        message.error('delete failed')
        throw data
      }
    },
    * reported({ payload }, { call, put }) {
      const data = yield call(reported,payload)
      if (data.success) {
        yield put({ type: 'query' })
      } else {
        throw data
      }
    }
  },
  reducers: {
    updateSelectState (state, { payload }) {
      return { ...state, ...payload }
    },
    updateEditState (state, { payload }) {
      return { ...state, ...payload }
    },
  },
})
